<template>
  <div class="container">
    <!-- 工具条 -->
    <el-form :inline="true" :data="positionData" :model="filters" class="demo-form-inline" style="margin-top:40px">
      <div class="newButton">
        <el-form-item>
          <el-button type="primary" size="small" @click="handleAdd"><svg-icon icon-class="add" style="cursor:pointer"/> 新增</el-button>
        </el-form-item>
        <el-form-item @selection-change="selsChange">
          <!-- <template slot-scope="scope"> -->
          <el-button :disabled="sels.length===0" type="primary" size="small" style="background-color:purple;border-color:purple" @click="handlePermission">权限配置</el-button>
          <!-- </template> -->
        </el-form-item>
      </div>
    </el-form>
    <!-- 列表 -->
    <div class="initList">
      <el-table v-loading="listLoading" :data="positionData" highlight-current-row style="width: 100%;" @selection-change="selsChange">
        <el-table-column type="selection"/>
        <el-table-column type="index"/>
        <el-table-column prop="departmentDes" label="所属部门"/>
        <el-table-column prop="positionDes" label="职位名称"/>
        <el-table-column prop="createTime" label="添加时间"/>
        <el-table-column prop="sort" label="排序"/>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="success" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--工具条-->
    <el-col ref="row" :span="24" style="background-color: aliceblue">
      <div style="margin:10px">
        <el-button :disabled="sels.length===0" type="danger" @click="batchRemove" >批量删除</el-button>
        <div class="block" style="float:right;padding:5px 0">
          <el-pagination
            :total="total"
            :current-page.sync="page"
            layout="prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </div>
    </el-col>
    <!-- 权限配置界面 -->
    <el-dialog :visible.sync="permissionFormVisible" :close-on-click-modal="false" title="权限配置" style="z-index:9999;">
      <div class="block">
        <el-tree
          ref="treePermission"
          :data="data"
          show-checkbox
          node-key="id">
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer" style="dispaly:block;text-align:center">
          <el-button :loading="permissionLoading" type="primary" size="mini" @click.native="addPermissionSubmit">提交</el-button>
          <el-button size="mini" style="margin-right:50px;margin-top:20px" @click.native="permissionFormVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 所属部门配置界面 -->
    <el-dialog :visible.sync="departmentsFormVisible" :close-on-click-modal="false" title="所属部门" style="z-index:9999;">
      <div class="block">
        <el-tree
          ref="treeDepartments"
          :props="defaultProps1"
          :data="parentIdData1"
          :check-strictly="true"
          :highlight-current="true"
          :expand-on-click-node="false"
          node-key="id"
          show-checkbox
          @check-change="checkChange1"
          @node-click="nodeClick1">
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer" style="dispaly:block;text-align:center">
          <el-button :loading="departmentsLoading" type="primary" size="mini" @click.native="addDepartmentSubmit">提交</el-button>
          <el-button size="mini" style="margin-right:50px;margin-top:20px" @click.native="departmentsFormVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 上级职位配置界面 -->
    <el-dialog :visible.sync="positionsFormVisible" :close-on-click-modal="false" title="上级职位" style="z-index:9999;">
      <div class="block">
        <el-tree
          ref="treePositions"
          :props="defaultProps"
          :data="parentIdData"
          :check-strictly="true"
          :highlight-current="true"
          :expand-on-click-node="false"
          node-key="id"
          show-checkbox
          @check-change="checkChange"
          @node-click="nodeClick">
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer" style="dispaly:block;text-align:center">
          <el-button :loading="positionsLoading" type="primary" size="mini" @click.native="addPositionsSubmit">提交</el-button>
          <el-button size="mini" style="margin-right:50px;margin-top:20px" @click.native="positionsFormVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--新增界面-->
    <el-dialog :visible.sync="addFormVisible" :close-on-click-modal="false" title="新增" style="z-index:9999">
      <el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="80px">
        <el-form-item label="职位名称" prop="positionDes">
          <el-input v-model="addForm.positionDes" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentDes">
          <el-input v-model="addForm.departmentDes" auto-complete="off" @focus="f1()"/>
        </el-form-item>
        <el-form-item label="上级职位" prop="parentPosition">
          <el-input v-model="addForm.parentPosition" auto-complete="off" @focus="f2()"/>
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input v-model="addForm.sort" auto-complete="off"/>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="addLoading" type="primary" @click.native="addSubmit">提交</el-button>
        <el-button @click.native="addFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!--编辑界面-->
    <el-dialog :visible.sync="editFormVisible" :close-on-click-modal="false" title="编辑">
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="80px">
        <el-form-item label="职位名称" prop="positionDes">
          <el-input v-model="editForm.positionDes" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentDes">
          <el-input v-model="editForm.departmentDes" auto-complete="off" @focus="f1()"/>
        </el-form-item>
        <el-form-item label="上级职位" prop="parentPosition">
          <el-input v-model="editForm.parentPosition" auto-complete="off" @focus="f2()"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="editLoading" type="primary" @click.native="editSubmit">提交</el-button>
        <el-button @click.native="editFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Search from '@/components/Search/index'
import { mapGetters } from 'vuex'
import { getPositionListPage, removePosition, batchRemoveposition, editPosition, addPosition, getPermissionListPage, addPositionsPermission, getPositionsListPage, getDepartmentListPage } from '@/api/position'
export default {
  name: 'Position',
  components: {
    Search
  },
  data() {
    const data = [{
      label: '111'
    }]
    return {
      flag: 0,
      data: JSON.parse(JSON.stringify(data)),
      parentIdData: JSON.parse(JSON.stringify(data)), // 后台返回上级职位树
      parentIdData1: JSON.parse(JSON.stringify(data)), // 后台返回所属部门树
      filters: {
        position: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultProps1: {
        children: 'children',
        label: 'label'
      },
      editCheckId: '',
      editCheckId1: '',
      parentposition: '',
      parentId: '',
      parentId1: '',
      parentTest: '',
      positionPermissions: [],
      positionData: [],
      newposition: '',
      total: 1,
      page: 2,
      listLoading: false,
      positionsLoading: false,
      departmentsLoading: false,
      addLoading: false,
      editLoading: false,
      permissionLoading: false,
      addFormVisible: false,
      positionsFormVisible: false,
      departmentsFormVisible: false,
      permissionFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      sels: [], // 列表选中列
      addForm: {
        positionDes: '',
        departmentDes: '',
        parentPosition: ''
      },
      // 编辑界面数据
      editForm: {
        positionDes: '',
        departmentDes: '',
        parentPosition: ''
      },
      addFormRules: {
        positionDes: [{ required: true, message: '请输入你要新增的职位名称', trigger: 'blur' }],
        departmentDes: [{ required: true, message: '请选择你要新增职位的所属部门', trigger: 'change' }]
      },
      editFormRules: {
        positionDes: [{ required: true, message: '请输入你要修改的职位名称', trigger: 'blur' }],
        departmentDes: [{ required: true, message: '请选择你要修改职位的所属部门', trigger: 'change' }]
      },
      count: 10
    }
  },
  computed: {
    ...mapGetters([
      'description',
      'position'
    ])
  },
  mounted() {
    this.getPermission()
    this.getPositions()
    this.getParentpositions()
    this.getParenDepartments()
  },
  methods: {
    f1() {
      console.log('获取所属部门的树')
      this.departmentsFormVisible = true
    },
    f2() {
      console.log('获取上级职位的树')
      this.positionsFormVisible = true
    },
    // 单选复选框操作
    checkChange(item, node, self) {
      if (node === true) { // 点击未选中复选框
        this.editCheckId = item.id
        this.$refs.treePositions.setCheckedKeys([item.id])
      } else {
        if (this.editCheckId === item.id) { // 点击已选中复选框，保证至少一个选中
          this.$refs.treePositions.setCheckedKeys([])
        }
      }
    },
    checkChange1(item, node, self) {
      if (node === true) { // 点击未选中复选框
        this.editCheckId1 = item.id
        this.$refs.treeDepartments.setCheckedKeys([item.id])
      } else {
        if (this.editCheckId1 === item.id) { // 点击已选中复选框，保证至少一个选中
          this.$refs.treeDepartments.setCheckedKeys([])
        }
      }
    },
    // 获取权限配置列表
    getPermission() {
      getPermissionListPage().then((res) => {
        this.data = res.data
      })
    },
    selectPosition() {
      this.parentPosition = this.$refs.treePositions.getCheckedNodes()[0].label
      this.parentId = this.$refs.treePositions.getCheckedNodes()[0].id
      console.log('selectPosition：' + this.parentPosition)
      console.log(this.parentId)
      this.positionsLoading = true
    },
    // 选择上级职位
    addPositionsSubmit: function() {
      if (this.flag === 0) {
        this.selectPosition()
        this.addForm.parentPosition = this.parentPosition
        this.positionsLoading = false
        this.positionsFormVisible = false
      } else {
        this.selectPosition()
        this.editForm.parentPosition = this.parentPosition
        this.positionsLoading = false
        this.positionsFormVisible = false
      }
    },
    selectDepartment() {
      this.departmentDes = this.$refs.treeDepartments.getCheckedNodes()[0].label
      this.parentId1 = this.$refs.treeDepartments.getCheckedNodes()[0].id
      console.log('selectDepartment:' + this.departmentDes)
      console.log(this.parentId1)
      this.departmentsLoading = true
    },
    // 选择所属部门
    addDepartmentSubmit: function() {
      if (this.flag === 0) {
        this.selectDepartment()
        this.addForm.departmentDes = this.departmentDes
        this.departmentsLoading = false
        this.departmentsFormVisible = false
      } else {
        this.selectDepartment()
        this.editForm.departmentDes = this.departmentDes
        this.departmentsLoading = false
        this.departmentsFormVisible = false
      }
    },
    nodeClick1(item, node, self) {
      this.editCheckId1 = item.id
      this.$refs.treeDepartments.setCheckedKeys([item.id])
    },
    nodeClick(item, node, self) {
      this.editCheckId = item.id
      this.$refs.treePositions.setCheckedKeys([item.id])
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.addForm = {
        departmentDes: '',
        positionDes: '',
        parentPosition: ''
      }
      this.flag = 0
    },
    // 显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      const edit = Object.assign({}, row)
      this.editForm = {
        departmentDes: edit.departmentDes,
        positionDes: edit.positionDes,
        parentPosition: edit.parentPosition,
        id: edit.id
      }
      this.flag = 1
    },
    // 权限配置
    handlePermission: function(index, row) {
      this.permissionFormVisible = true
      this.permissionForm = Object.assign({}, row)
    },
    // 提交权限修改列表
    addPermissionSubmit: function() {
      var positions = this.sels.map(item => item.position)
      const myData = JSON.stringify({ positions: positions })
      console.log(myData)
      this.positionPermissions = this.$refs.treePermission.getCheckedKeys()
      console.log(this.positionPermissions)
      this.$confirm('确认要给该角色添加权限吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.permissionLoading = true
        const para = {
          positions: positions,
          positionPermissions: this.positionPermissions
        }
        console.log(para.positions)
        addPositionsPermission(para.positions, para.positionPermissions).then((res) => {
          this.permissionLoading = false
          this.permissionFormVisible = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getPositions()
        })
      }).catch(() => {

      })
    },
    // 获取上级职位配置列表
    getParentpositions() {
      getPositionsListPage().then((res) => {
        this.parentIdData = res.data
        console.log(res.data)
      })
    },
    // 获取所属部门配置列表
    getParenDepartments() {
      getDepartmentListPage().then((res) => {
        this.parentIdData1 = res.data
        console.log(res.data)
      })
    },
    handleSizeChange(val) {
      console.log(`${val} items per page`)
    },
    handleCurrentChange(val) {
      this.page = val
      this.getPositions()
    },
    selsChange: function(sels) {
      this.sels = sels
    },
    // 显示所有职位列表
    getPositions() {
      const para = {
        page: this.page,
        count: 10
      }
      this.listLoading = true
      getPositionListPage(para).then((res) => {
        this.total = res.data.sums
        console.log(this.total)
        this.positionData = res.data.result
        this.listLoading = false
      })
    },
    // 删除
    handleDel: function(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        const para = [row.id]
        removePosition(para).then((res) => {
          this.listLoading = false
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getPositions()
        })
      }).catch(() => {

      })
    },
    // 批量删除
    batchRemove: function() {
      var ids = this.sels.map(item => item.id)
      const myData = JSON.stringify({ id: ids })
      console.log(myData)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        batchRemoveposition(ids).then((res) => {
          this.listLoading = false
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getPositions()
        })
      }).catch(() => {

      })
    },
    // 编辑提交
    editSubmit: function() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            const para = Object.assign({}, this.editForm)
            console.log(para)
            const myPara = {
              positionDes: para.positionDes,
              id: para.id
            }
            if (typeof (this.$refs.treeDepartments) !== 'undefined' && this.$refs.treeDepartments.getCheckedNodes().length !== 0) {
              myPara.departmentDes = this.$refs.treeDepartments.getCheckedNodes()[0].id
            }
            if (typeof (this.$refs.treePositions) !== 'undefined' && this.$refs.treePositions.getCheckedNodes().length !== 0) {
              myPara.parentPosition = this.$refs.treePositions.getCheckedNodes()[0].id
            }
            editPosition(myPara).then((res) => {
              this.editLoading = false
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.$refs['editForm'].resetFields()
              this.editFormVisible = false
              this.getPositions()
            })
          })
        }
      })
    },
    // 保存新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            const para = Object.assign({}, this.addForm)
            console.log(para)
            const myPara = {
              positionDes: para.positionDes,
              departmentDes: this.$refs.treeDepartments.getCheckedNodes()[0].id
            }
            // if (this.$refs.treePositions.getCheckedNodes()[0].id !== null && this.$refs.treePositions.getCheckedNodes()[0].id.length !== 0) {
            //   myPara.parentPosition = this.$refs.treePositions.getCheckedNodes()[0].id
            // }
            addPosition(myPara).then((res) => {
              this.addLoading = false
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.$refs['addForm'].resetFields()
              this.addFormVisible = false
              this.getPositions()
            })
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .container{
    width: 94%;
    margin-left: 3%;
    height: 100%;
  }
  .el-dialog{
    width: 800px
  }
  .el-loading-mask{
    z-index: 1000;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .table-list{
    width: 100%;
  }
  .permissionLabel{
    display: flex;
    float: left;
    margin-right: 5px
  }
  .search {
    background-color: white;
    width: 100%;
    height: 100%;
    padding: 20px 20px 0 20px;
    margin-bottom: 30px
  }
  .newButton {
    background-color: white;
    width: 100%;
    height: 100%;
    padding: 20px 20px 0 20px;
    .el-form-item {
      margin-bottom: 0px
    }
  }
</style>
